package com.oa.ylms.apps.dao.archives.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.dao.archives.IRecordInfoDao;
import com.oa.ylms.apps.entity.archives.RecordInfoValue;

public class RecordInfoDaoImpl extends HibernateDaoSupport implements
		IRecordInfoDao {
	List<RecordInfoValue> list;

	@Override
	public int addRecordInfo(RecordInfoValue recordInfo) throws Exception {
		if(recordInfo != null){
			this.getHibernateTemplate().save(recordInfo);
			recordInfo.getRecordId();
		}
		return 0;
	}

	@Override
	public boolean deleteRecordInfo(RecordInfoValue recordInfo)
			throws Exception {
		if(recordInfo != null){
			try{
				this.getHibernateTemplate().delete(recordInfo);
			}catch(Exception e){
				return false;
			}
			return true;
		}
		return false;
	}

	@Override
	public boolean modifyRecordInfo(RecordInfoValue recordInfo)
			throws Exception {
		if(recordInfo != null){
			try{
				this.getHibernateTemplate().update(recordInfo);
			}catch(Exception e){
				return false;
			}
			return true;
		}
		return false;
	}

	@Override
	public RecordInfoValue queryByRecordId(RecordInfoValue recordInfo)
			throws Exception {
		if(recordInfo != null){
			return (RecordInfoValue) this.getHibernateTemplate().get(RecordInfoValue.class, recordInfo.getRecordId());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<RecordInfoValue> queryRecordInfo(final RecordInfoValue recordInfo)
			throws Exception {
		if(recordInfo != null){
			String hqlStr = "FROM RecordInfoValue riv WHERE 1=1";
			if(recordInfo.getRecordCategory() != null){
				hqlStr += " AND riv.recordCategory = ?";
			}
			if(recordInfo.getArchiveInfo() != null){
				hqlStr += " AND riv.archiveInfo = ?";
			}
			final String hql = hqlStr;
			list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
				public Object doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query query = session.createQuery(hql);
					int index = -1;
					if(recordInfo.getRecordCategory() != null){
						query.setEntity(++index, recordInfo.getRecordCategory());
					}
					if(recordInfo.getArchiveInfo() != null){
						query.setEntity(++index, recordInfo.getArchiveInfo());
					}
					list = query.list();
					return list;
				}
			});
			return list;
		}
		return null;
	}
	
	public List<RecordInfoValue> getList() {
		return list;
	}

	public void setList(List<RecordInfoValue> list) {
		this.list = list;
	}
	
}
